/*
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-11-12 12:18:32
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-05 22:24:33
 */
import { useAppStore } from "@/store";
import router from "@/routes";

const allPerms: { grantedPolicies: Array<string> } = {
  grantedPolicies: [],
};

/**
 *
 * @returns
 */
const getAllPermissions = () => {
  if (allPerms.grantedPolicies.length > 0) {
    return allPerms.grantedPolicies;
  }
  const appStore = useAppStore();
  let perms = Object.keys(appStore.grantedPolicies);
  allPerms.grantedPolicies = perms;
  return perms;
};

/**
 * 检查权限
 * @param permissionName
 */
export function checkPermission(permissionName: string) {
  if (!permissionName || permissionName.trim() == "") {
    return true;
  }
  let isPermission: boolean;
  let perms = getAllPermissions();
  if (!perms || perms.length === 0) {
    isPermission = false;
  } else {
    isPermission = perms.findIndex((x) => x.startsWith(permissionName)) !== -1;
  }
  return isPermission;
}

/**
 * 判断权限数据是否已加载
 */
export function isReadyPermission() {
  let perms = getAllPermissions();
  return perms && perms.length > 0;
}

/**
 * 检查操作权限
 * @param action
 * @returns
 */
export function checkAction(action: string) {
  if (!action) {
    return;
  }
  const meta = router.currentRoute.value.meta;
  const module = meta.permissionCode || "";
  const isFullName = !module || action?.indexOf(".") >= 0;
  const permissionName = isFullName ? action : [module, action].join(".");
  return checkPermission(permissionName);
}

export function checkActionStyle(action: string) {
  if (checkAction(action)) {
    return {};
  } else {
    return { display: "none" };
  }
}

export function clearAuthPermissions() {
  allPerms.grantedPolicies = [];
}
